﻿using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;

/// <summary>
/// Redis 访问服务
/// </summary>
public class RedisService
{
    private readonly ConnectionMultiplexer _redis;
    private readonly IDatabase _db;
    private readonly IConfiguration _configuration;

    public RedisService(IConfiguration configuration)
    {
        _configuration = configuration;
        _redis = ConnectionMultiplexer.Connect(_configuration["Redis:ConnectionString"]);
        _db = _redis.GetDatabase();
    }

    /// <summary>
    /// 存储 JWT 令牌（用于黑名单机制）
    /// </summary>
    /// <param name="token">JWT 令牌</param>
    /// <param name="expireMinutes">过期时间</param>
    /// <returns></returns>
    public async Task AddTokenToBlacklist(string token, int expireMinutes)
    {
        string key = _configuration["Redis:TokenPrefix"] + token;
        await _db.StringSetAsync(key, "blacklisted", TimeSpan.FromMinutes(expireMinutes));
    }

    /// <summary>
    /// 检查 JWT 是否在黑名单中
    /// </summary>
    /// <param name="token">JWT 令牌</param>
    /// <returns>是否在黑名单</returns>
    public async Task<bool> IsTokenBlacklisted(string token)
    {
        string key = _configuration["Redis:TokenPrefix"] + token;
        return await _db.KeyExistsAsync(key);
    }
}
